import base64
import os.path

from flask import (
    Blueprint, request, session, current_app, send_from_directory
)

from .db import get_db

# from .auth import login_required

bp = Blueprint('user', __name__, url_prefix='/user')


@bp.route('/history', methods=['GET'])
def user_history():
    cur = get_db()
    if request.method == 'GET':
        UID = session.get("UID")
        if UID is None:
            UID = 10000
        # return current_app.send_static_file('drawing.html')
        cur.execute(f"SELECT task_info FROM drawing WHERE uid={UID} ORDER BY creating_time")
        user_tasks = cur.fetchall()
        user_task1 = [task[0] for task in user_tasks]
        print(user_task1)
        return user_task1


@bp.route('/profile', methods=['GET'])
def get_profile():
    return send_from_directory(os.path.join(current_app.root_path, 'static'), 'profile.html')


@bp.route('/profile/<int:uid>', methods=['GET'])
def get_other_profile(uid):
    session['next_profile_uid'] = uid
    return send_from_directory(os.path.join(current_app.root_path, 'static'), 'profile.html')


@bp.route('/profile/avatar', methods=['POST'])
# @login_required
def operate_avatar():
    UID = session.get('next_profile_uid')
    if UID is None:
        UID = session.get("UID")
    db = get_db()
    operation = request.json['operation']
    avatar_byte = base64.b64decode(request.json['avatar'])
    if operation == 'modify':
        with open(os.path.join(current_app.root_path, 'static', 'drawing_result', (UID + '.png')), 'wb') as f:
            f.write(avatar_byte)
            f.flush()
        db.execute(f"UPDATE _user SET avatar={(UID + '.png')} WHERE uid='{UID}'")
    if operation == 'delete':
        db.execute(f"UPDATE _user SET avatar={'default.png'} WHERE uid='{UID}'")


@bp.route('/profile/avatar', methods=['GET'])
def get_self_avatar():
    UID = session.get('next_profile_uid')
    if UID is None:
        UID = session.get("UID")
    return get_avatar(UID)


@bp.route('/profile/avatar/<string:uid>', methods=['GET'])
def get_avatar(uid):
    db = get_db()
    db.execute(f"SELECT avatar FROM _user WHERE uid='{uid}'")
    uid = db.fetchone()
    if uid[0] is None:
        uid = 'default'
    else:
        uid = uid[0]
    return send_from_directory(os.path.join(current_app.root_path, 'static', 'avatar'), uid + '.png')


@bp.route('/profile/info', methods=['GET', 'POST'])
def info():
    UID = session.get('next_profile_uid')
    if UID is None:
        UID = session.get("UID")
    db = get_db()
    if request.method == 'GET':
        db.execute(f"SELECT * FROM _user WHERE uid='{UID}'")
        row = db.fetchone()
        return {
            "UID": row[0],
            "nickname": row[2],
            "email": row[3],
        }

    if request.method == 'POST':
        avatar_byte = base64.b64decode(request.json['avatar'])
        with open(os.path.join(current_app.root_path, 'static', 'drawing_result', (UID + '.png')), 'wb') as f:
            f.write(avatar_byte)
            f.flush()
        db.execute(f"UPDATE _user SET avatar={(UID + '.png')} WHERE uid='{UID}'")
